<template>
  <div id="vedio">
    <room-container ref="TUIRoomRef"></room-container>
    <el-dialog title="请输入房间编号" :visible.sync="roomModal" width="30%">
      <el-input type="number" v-model="roomId" placeholder="请输入" autofocus></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roomModal = false">取 消</el-button>
        <el-button type="primary" @click="handleEnterRoom">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import RoomContainer from "@/TUIRoom/index.vue";
import Vue from "vue";
import axios from "axios";
import { Message, Loading } from "element-ui";
import { TuiRoomInitParam } from "@/TuiRoomParams.ts";

export default Vue.extend({
  components: {
    RoomContainer,
  },
  data() {
    return {
      roomModal: true,
      roomId: null,
    };
  },
  async mounted() {
    // 6542dda38a84444c989a9332a616d672
    if (!this.$route.query.user) {
      Message.error("没有用户ID传入不可创建视频");
      return;
    }
  },
  methods: {
    async getUserSig(userId: string): Promise<typeof TuiRoomInitParam | false> {
      const response = await axios({
        method: "post",
        url: "/admin/getTencentUserSig",
        data: { userId, type: "client" },
      });
      if (response.status !== 200 && response.statusText !== "OK") {
        throw new Error("请求错误");
      }
      const { code, data } = response.data;
      if (code !== 200) {
        throw new Error(data);
      }
      return data;
    },
    // 普通成员进入房间，该方法在普通成员进入已创建好的房间时调用
    async handleEnterRoom() {
      const roomId = Number(this.roomId)
      if (!roomId || roomId < 0 || isNaN(roomId)) {
        Message.error("请输入有效的房间编号（大于1的数字）");
        return;
      }
      const loadingInstance = Loading.service({
        lock: true,
        text: "正在进入房间",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.3)",
      });
      try {
        const initParam: typeof TuiRoomInitParam & { roomId: number } =
          await this.getUserSig(this.$route.query.user as string);
        if (!initParam) return;
        const temp: any = this.$refs?.TUIRoomRef;
        // 初始化 TUIRoom 组件
        await temp?.init?.(initParam);
        // 进入房间
        await temp.enterRoom(roomId, {
          isOpenCamera: true,
          isOpenMicrophone: true,
        });
        this.roomModal = false
      } catch (error: any) {
        Message.error(error.message);
      } finally {
        loadingInstance.close();
      }
    },
  },
});
</script>

<style>
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}

#vedio {
  width: 100%;
  height: 100%;
}
</style>
